﻿using log4net;
using McsUtility;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MinerManager.Forms
{
	public partial class UserRegister : Form
	{
		ILog logger = LogManager.GetLogger(typeof(Program));
		private Common.AgentComponent Agent = null;

		private List<McsUtility.Models.StaffModel> infosStaff = new List<McsUtility.Models.StaffModel>();

		public UserRegister(Common.AgentComponent agent)
		{
			InitializeComponent();
			this.Agent = agent;
		}

		#region 窗体事件

		private void UserRegister_Load(object sender, EventArgs e)
		{
			this.Agent.OnNodeServerMinerManagerGetStaffs += new EventHandler<ByteEventArgs>(Agent_OnGetRegSmsCodeReceive);
			this.Agent.OnGetRegSmsCodeReceive += new EventHandler<ByteEventArgs>(Agent_OnGetRegSmsCode);
			this.Agent.OnManagerRegisterReceive += new EventHandler<ByteEventArgs>(Agent_OnManagerRegister);

			//连接服务器
			if (!this.Agent.IsStarted)
			{
				Common.ConnectionServer conn = new Common.ConnectionServer(this.Agent);
				conn.Connection();
			}

			byte[] bytes = ProtocolHelper.WritePackage(ProtoType.MinerManagerGetStaffs, "");
			this.Agent.AgentSend(bytes);
		}

		private void UserRegister_FormClosing(object sender, FormClosingEventArgs e)
		{
			this.Agent.OnNodeServerMinerManagerGetStaffs -= new EventHandler<ByteEventArgs>(Agent_OnGetRegSmsCodeReceive);
			this.Agent.OnGetRegSmsCodeReceive -= new EventHandler<ByteEventArgs>(Agent_OnGetRegSmsCode);
			this.Agent.OnManagerRegisterReceive -= new EventHandler<ByteEventArgs>(Agent_OnManagerRegister);
		}

		#endregion

		#region Agent事件

		private void Agent_OnGetRegSmsCodeReceive(object sender, ByteEventArgs e)
		{
			infosStaff = ProtocolHelper.ReadPackageBody<List<McsUtility.Models.StaffModel>>(e.Bytes);

			//获取默认客户经理
			string staffId = System.Configuration.ConfigurationManager.AppSettings["StaffId"];
			if (string.IsNullOrWhiteSpace(staffId))
				staffId = "2";
			
			//控件操作
			List<ComboboxListItem> items = new List<ComboboxListItem>();
			foreach(McsUtility.Models.StaffModel info in infosStaff)
			{
				items.Add(new ComboboxListItem() { Text = info.Name, Value = info.ID.ToString() });
			}
			Common.Utility.SetComboBox(this, "ItemStaffs", items, staffId);
		}

		private void Agent_OnGetRegSmsCode(object sender, ByteEventArgs e)
		{
			McsUtility.Models.ResultModel result = ProtocolHelper.ReadPackageBody<McsUtility.Models.ResultModel>(e.Bytes);
			if (!result.success)
				MessageBox.Show("短信发送失败，请检查手机号是否正确。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
		}

		private void Agent_OnManagerRegister(object sender, ByteEventArgs e)
		{
			McsUtility.Models.ResultModel result = ProtocolHelper.ReadPackageBody<McsUtility.Models.ResultModel>(e.Bytes);
			if (result.success)
			{
				MessageBox.Show("注册成功。", "成功", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
				Common.Utility.FormClose(this);
			}
			else
			{
				MessageBox.Show("注册失败。" + result.message + "。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#endregion

		#region void ItemStaffs_SelectedIndexChanged(object sender, EventArgs e)

		private void ItemStaffs_SelectedIndexChanged(object sender, EventArgs e)
		{
			StaffsQQ.Text = infosStaff[ItemStaffs.SelectedIndex].QQ1;
			StaffsWechat.Text = infosStaff[ItemStaffs.SelectedIndex].WeiXin1;
		}

		#endregion

		#region void BtnSendSMSCode_Click(object sender, EventArgs e)

		private void BtnSendSMSCode_Click(object sender, EventArgs e)
		{
			//非法信息检测
			if (string.IsNullOrWhiteSpace(ItemUserName.Text))
			{
				if (MessageBox.Show("请输入手机号。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemUserName.Focus();
					ItemUserName.SelectAll();
				}
				return;
			}

			if (!ItemUserName.Text.IsMobile())
			{
				if (MessageBox.Show("请输入正确的手机号。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemUserName.Focus();
					ItemUserName.SelectAll();
				}
				return;
			}

			ItemSMSCode.SelectAll();

			//连接服务器
			if (!this.Agent.IsStarted)
			{
				Common.ConnectionServer conn = new Common.ConnectionServer(this.Agent);
				conn.Connection();
			}

			//执行发送验证码
			Thread thread = new Thread(SendSMSCode);
			thread.IsBackground = true;
			thread.Start();
		}

		private void SendSMSCode()
		{
			SetBtnSendSMSCode(false);

			//发送验证码
			McsUtility.Models.LoginModel info = new McsUtility.Models.LoginModel
			{
				LoginName = ItemUserName.Text
			};
			byte[] bytes = ProtocolHelper.WritePackage<McsUtility.Models.LoginModel>(ProtoType.MinerManagerGetRegSmsCode, info);
			this.Agent.AgentSend(bytes);

			//倒计时
			int second = 60;
			while (true)
			{
				SetBtnSendSMSCode(false, "发送（" + second + "秒）");
				second--;
				Thread.Sleep(1000);

				if (second <= 0)
					break;
			}

			SetBtnSendSMSCode(true, "发送验证码");
		}

		private delegate void DelegateSetBtnSendSMSCode(bool enable, string text = "");
		private void SetBtnSendSMSCode(bool enable, string text = "")
		{
			if (BtnSendSMSCode.InvokeRequired)
			{
				DelegateSetBtnSendSMSCode d = new DelegateSetBtnSendSMSCode(SetBtnSendSMSCode);
				this.Invoke(d, enable, text);
			}
			else
			{
				BtnSendSMSCode.Enabled = enable;
				BtnSendSMSCode.Text = !string.IsNullOrWhiteSpace(text) ? text : BtnSendSMSCode.Text;
			}
		}

		#endregion

		#region void BtnRegister_Click(object sender, EventArgs e)

		private void BtnRegister_Click(object sender, EventArgs e)
		{
			int smsCode = 0;
			
			#region 非法信息检测

			if (string.IsNullOrWhiteSpace(ItemUserName.Text))
			{
				if (MessageBox.Show("请输入手机号。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemUserName.Focus();
					ItemUserName.SelectAll();
				}
				return;
			}

			if (!ItemUserName.Text.IsMobile())
			{
				if (MessageBox.Show("请输入正确的手机号。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemUserName.Focus();
					ItemUserName.SelectAll();
				}
				return;
			}

			if (string.IsNullOrWhiteSpace(ItemPassword.Text))
			{
				if (MessageBox.Show("请输入登录密码。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemPassword.Focus();
					ItemPassword.SelectAll();
				}
				return;
			}

			if (string.IsNullOrWhiteSpace(ItemPasswordConfirm.Text))
			{
				if (MessageBox.Show("请输入确认密码。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemPasswordConfirm.Focus();
					ItemPasswordConfirm.SelectAll();
				}
				return;
			}

			if (ItemPassword.Text != ItemPasswordConfirm.Text)
			{
				if (MessageBox.Show("登录密码与确认密码应输入相同字符。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemPasswordConfirm.Focus();
					ItemPasswordConfirm.SelectAll();
				}
				return;
			}

			if (string.IsNullOrWhiteSpace(ItemName.Text))
			{
				if (MessageBox.Show("请输入姓名。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemName.Focus();
					ItemName.SelectAll();
				}
				return;
			}

			if (string.IsNullOrWhiteSpace(ItemSMSCode.Text))
			{
				if (MessageBox.Show("请输入验证码。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemSMSCode.Focus();
					ItemSMSCode.SelectAll();
				}
				return;
			}

			if(!int.TryParse(ItemSMSCode.Text,out smsCode))
			{
				if (MessageBox.Show("请输入正确的验证码。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemSMSCode.Focus();
					ItemSMSCode.SelectAll();
				}
				return;
			}

			if (ItemStaffs.SelectedValue.ToString().ConvertInt() <= 0)
			{
				if (MessageBox.Show("请选择客户经理。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error) == DialogResult.OK)
				{
					ItemStaffs.Focus();
				}
				return;
			}

			#endregion

			//连接服务器
			if (!this.Agent.IsStarted)
			{
				Common.ConnectionServer conn = new Common.ConnectionServer(this.Agent);
				conn.Connection();
			}

			if (this.Agent.IsStarted)
			{
				McsUtility.Models.RegModel info = new McsUtility.Models.RegModel
				{
					LoginName = ItemUserName.Text.Trim(),
					LoginPass = ItemPassword.Text,
					SMSCode = smsCode,
					Name = ItemName.Text.Trim(),
					PassQuestion1 = ItemPassQuestion1.Text.Trim(),
					PassQuestion2 = ItemPassQuestion2.Text.Trim(),
					PassQuestion3 = ItemStaffs.SelectedValue.ToString(),
					PassAnswer1 = "",
					PassAnswer2 = "",
					PassAnswer3 = "",
					CardID = "",
					Sex = 1
				};
				byte[] bytes = ProtocolHelper.WritePackage<McsUtility.Models.RegModel>(ProtoType.MinerManagerReg, info);
				this.Agent.AgentSend(bytes);
			}
			else
			{
				MessageBox.Show("服务器连接已断开，请检查网络是否畅通后重新注册。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		#endregion

		#region void BtnClose_Click(object sender, EventArgs e)

		private void BtnClose_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		#endregion



		#region void TextBox_KeyPress(object sender, KeyPressEventArgs e)

		private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
		{
			if (e.KeyChar == 13)
			{
				e.Handled = true;
				BtnRegister_Click(BtnRegister, new EventArgs());
			}

			if (e.KeyChar == 27)
			{
				e.Handled = true;
				BtnClose_Click(BtnClose, new EventArgs());
			}
		}

		#endregion
	}
}
